package com.pactera.madp.cp.service.sync.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pactera.madp.cp.api.entity.sync.SyncPreSavedeptInfoEntity;
import com.pactera.madp.cp.common.constant.Constants;
import com.pactera.madp.cp.common.util.sync.SyncUtils;
import com.pactera.madp.cp.config.SyncConfig;
import com.pactera.madp.cp.context.SyncStateContext;
import com.pactera.madp.cp.mapper.sync.SyncPreSavedeptInfoMapper;
import com.pactera.madp.cp.service.sync.SyncPreSavedeptInfoHisService;
import com.pactera.madp.cp.service.sync.SyncPreSavedeptInfoService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
@AllArgsConstructor
public class SyncPreSavedeptInfoServiceImpl extends ServiceImpl<SyncPreSavedeptInfoMapper, SyncPreSavedeptInfoEntity> implements SyncPreSavedeptInfoService {

    private final SyncPreSavedeptInfoHisService syncPreSavedeptInfoHisService;
    private final SyncConfig syncConfig;
    // 设置存储阀值，每当数据量达到以下值时进行一次数据库保存
    // 该值需根据mysql的max_allowed_packet变量大小进行设置
    private final int PER_SAVE_COUNTS = 10000;

    @Override
    public void addYesterdayToHis() {
        /*log.debug("活期余额信息：addYesterdayToHis");
        String date = DateUtil.format(new Date(), Constants.DATE_FORMAT);

        String fileDate = SyncStateContext.get().getFileDate();
        if (StrUtil.isNotEmpty(fileDate)) {
            date = fileDate;
        }
        syncPreSavedeptInfoHisService.syncOneDay(date);*/
    }

    @Override
    public void deleteYesterday() {
    }

    @Override
    public void parse() {
        log.debug("活期余额信息：parse");
        String filepath = SyncUtils.buildFilePath(syncConfig.getCrmPath(), Constants.FN_PRE_SAVEDEPT, SyncStateContext.get().getFileDate());
        File newestFile = SyncUtils.getNewestFile(filepath);

        List<String> lines = new ArrayList<>();

        int perCounts = syncConfig.getCrmPerCounts() == null ? PER_SAVE_COUNTS : syncConfig.getCrmPerCounts();

        Object[] tempData = SyncStateContext.get().getTempData();
        long n = (long) tempData[1];

        // 文件为Windows格式补2个字符，Unix格式补1个字符
        int fillChar = 1;
        List result = SyncUtils.segmentReadFile(newestFile, syncConfig.getCrmCharset(), n, fillChar, perCounts, lines);
        tempData[0] = result.get(0);
        tempData[1] = result.get(1);

        int counts = doBatchSaveOrUpdate(lines);

        int totalCount = (int) tempData[2] + counts;
        tempData[2] = totalCount;
        log.info("已同步CRM活期余额数据量：{}, 已读文件字符数：{}", totalCount, tempData[1]);
    }

    @Override
    public void deleteHisOneDay() {
        /*log.debug("活期余额信息：deleteHisOneDay");
        DateTime offsetDay = DateUtil.offsetDay(new Date(), -1);

        String fileDate = SyncStateContext.get().getFileDate();
        if (StrUtil.isNotEmpty(fileDate)) {
            offsetDay = DateUtil.offsetDay(DateUtil.parse(fileDate, Constants.DATE_FORMAT), -1);
        }
        String date = DateUtil.format(offsetDay, Constants.DATE_FORMAT);

        syncPreSavedeptInfoHisService.deleteOneDate(date);*/
    }

    @Override
    public void syncBusiness() {
        log.debug("活期余额信息：syncBusiness");
        // 设置执行最终状态
        Object[] tempData = SyncStateContext.get().getTempData();
        boolean isContinue = (boolean) tempData[0];
        if (isContinue) {
            SyncStateContext.get().setFinalState(false);
        } else {
            SyncStateContext.get().setFinalState(true);
        }
    }

    /**
     * 存储更新数据
     * @param lines
     */
    private int doBatchSaveOrUpdate(List<String> lines) {
        List<SyncPreSavedeptInfoEntity> entityList = SyncUtils.parse(lines, Constants.SEPARATOR_VERTICAL_LINE, SyncPreSavedeptInfoEntity.class);
        if (!entityList.isEmpty()) {
            this.saveOrUpdateBatch(entityList);
        }
        SyncStateContext.get().getTempData()[3] = entityList;

        return entityList.size();
    }

}
